/**
 * 动态加载百度地图API
 * @param ak 百度地图开发者AK
 * @returns Promise<void>
 */
export const loadBMap = (ak: string): Promise<void> => {
  return new Promise((resolve, reject) => {
    // 检查是否已加载
    if (typeof window.BMap !== 'undefined') {
      resolve();
      return;
    }

    // 创建script标签
    const script = document.createElement('script');
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=${ak}&callback=onBMapLoaded`;
    script.async = true;
    script.defer = true;

    // 定义全局回调函数
    window.onBMapLoaded = () => {
      resolve();
      // 清理全局回调
      delete window.onBMapLoaded;
    };

    script.onerror = () => {
      reject(new Error('百度地图加载失败'));
      // 清理全局回调
      delete window.onBMapLoaded;
    };

    document.head.appendChild(script);
  });
};
